<?php
namespace app\controller;

use app\BaseController;
use app\model\SystemConfig;
use think\facade\Log;
use GuzzleHttp\Client;

class AiToolController extends BaseController
{
    protected $apiKey;
    protected $model;
    protected $client;
    protected $apiEndpoint;

    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize();
        $this->apiKey = SystemConfig::getConfig('openai_api_key');
        $this->model = SystemConfig::getConfig('openai_model', 'gpt-3.5-turbo');
        $this->apiEndpoint = SystemConfig::getConfig('ai_api_url', 'https://api.openai.com/v1/chat/completions');
        $this->client = new Client();
    }

    /**
     * 聊天消息分析
     * @param string $content 消息内容
     * @return array ['summary' => '摘要', 'keywords' => ['关键词1', '关键词2']]
     */
    public function analyzeMessage($content)
    {
        $prompt = "请分析以下内容，提供简短的摘要和关键词（最多5个）：\n\n{$content}";
        
        try {
            $response = $this->sendRequest([
                [
                    'role' => 'system',
                    'content' => '你是一个专业的文本分析助手，请提供准确的摘要和关键词。'
                ],
                [
                    'role' => 'user',
                    'content' => $prompt
                ]
            ]);

            // 解析AI回复，提取摘要和关键词
            $result = $this->parseAnalysisResult($response);
            return [
                'status' => 200,
                'data' => $result
            ];
        } catch (\Exception $e) {
            Log::error('消息分析失败：' . $e->getMessage());
            return [
                'status' => 500,
                'message' => '分析失败：' . $e->getMessage()
            ];
        }
    }

    /**
     * 会话历史总结
     * @param array $messages 历史消息数组
     * @return array ['summary' => '总结', 'keywords' => ['关键词1', '关键词2']]
     */
    public function summarizeSession($messages)
    {
        $history = '';
        foreach ($messages as $msg) {
            $role = $msg['is_ai'] ? 'AI' : '用户';
            $history .= "{$role}: {$msg['content']}\n";
        }

        $prompt = "请总结以下对话内容，提供简洁的摘要和主要关键词：\n\n{$history}";

        try {
            $response = $this->sendRequest([
                [
                    'role' => 'system',
                    'content' => '你是一个专业的对话分析助手，请提供准确的对话总结和关键词。'
                ],
                [
                    'role' => 'user',
                    'content' => $prompt
                ]
            ]);

            $result = $this->parseAnalysisResult($response);
            return [
                'status' => 200,
                'data' => $result
            ];
        } catch (\Exception $e) {
            Log::error('会话总结失败：' . $e->getMessage());
            return [
                'status' => 500,
                'message' => '总结失败：' . $e->getMessage()
            ];
        }
    }

    /**
     * 智能回复生成
     * @param array $context 上下文消息数组
     * @param string $lastMessage 最新消息
     * @return string 生成的回复
     */
    public function generateReply($context, $lastMessage)
    {
        $messages = [
            [
                'role' => 'system',
                'content' => '你是一个专业、友好的AI助手，请根据上下文提供恰当的回复。'
            ]
        ];

        // 添加上下文消息
        foreach ($context as $msg) {
            $role = $msg['is_ai'] ? 'assistant' : 'user';
            $messages[] = [
                'role' => $role,
                'content' => $msg['content']
            ];
        }

        // 添加最新消息
        $messages[] = [
            'role' => 'user',
            'content' => $lastMessage
        ];

        try {
            $response = $this->sendRequest($messages);
            return [
                'status' => 200,
                'data' => [
                    'reply' => $response
                ]
            ];
        } catch (\Exception $e) {
            Log::error('回复生成失败：' . $e->getMessage());
            return [
                'status' => 500,
                'message' => '生成回复失败：' . $e->getMessage()
            ];
        }
    }

    /**
     * 项目分析
     * @param array $project 项目信息
     * @param array $reminders 相关提醒
     * @return array 分析结果
     */
    public function analyzeProject($project, $reminders)
    {
        $content = "项目名称：{$project['name']}\n";
        $content .= "项目目标：{$project['goal']}\n";
        $content .= "项目描述：{$project['description']}\n\n";
        $content .= "相关提醒：\n";
        
        foreach ($reminders as $reminder) {
            $content .= "- {$reminder['title']}\n";
        }

        $prompt = "请分析以下项目信息，提供项目进展建议和可能的风险点：\n\n{$content}";

        try {
            $response = $this->sendRequest([
                [
                    'role' => 'system',
                    'content' => '你是一个专业的项目分析助手，请提供有价值的建议和风险提示。'
                ],
                [
                    'role' => 'user',
                    'content' => $prompt
                ]
            ]);

            return [
                'status' => 200,
                'data' => [
                    'analysis' => $response
                ]
            ];
        } catch (\Exception $e) {
            Log::error('项目分析失败：' . $e->getMessage());
            return [
                'status' => 500,
                'message' => '分析失败：' . $e->getMessage()
            ];
        }
    }

    /**
     * 发送API请求
     */
    protected function sendRequest($messages)
    {
        if (empty($this->apiKey)) {
            throw new \Exception('未配置API密钥');
        }

        try {
            $response = $this->client->post($this->apiEndpoint, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $this->apiKey,
                    'Content-Type' => 'application/json',
                ],
                'json' => [
                    'model' => $this->model,
                    'messages' => $messages,
                    'temperature' => 0.7,
                    'max_tokens' => 1000
                ]
            ]);

            $result = json_decode($response->getBody(), true);
            return $result['choices'][0]['message']['content'] ?? '';
        } catch (\Exception $e) {
            throw new \Exception('API请求失败：' . $e->getMessage());
        }
    }

    /**
     * 解析分析结果
     */
    protected function parseAnalysisResult($response)
    {
        // 期望的回复格式：
        // 摘要：xxx
        // 关键词：xxx, xxx, xxx
        
        $lines = explode("\n", $response);
        $summary = '';
        $keywords = [];

        foreach ($lines as $line) {
            if (strpos($line, '摘要：') === 0) {
                $summary = trim(substr($line, strlen('摘要：')));
            } elseif (strpos($line, '关键词：') === 0) {
                $keywordStr = trim(substr($line, strlen('关键词：')));
                $keywords = array_map('trim', explode(',', $keywordStr));
            }
        }

        return [
            'summary' => $summary,
            'keywords' => $keywords
        ];
    }
} 